package com.hula.onion.book.server.spider.platforms.duoduolicai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by work on 2018/1/29.
 */
@Component
public class DuoDuoLiCaiSpiderHelper {
    private static final Logger logger = LoggerFactory.getLogger(DuoDuoLiCaiSpiderHelper.class);
    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("phone", form.getUserName());
        map.put("password", form.getPassword());
        map.put("_", System.currentTimeMillis());
        return map;
    }

    /**
     * 解析账户余额
     *
     * @param accountStr
     * @return
     */
    public CommonResponse parseAccountBalance(String accountStr) {
        if (StringUtils.isEmpty(accountStr)) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
        try {
            JSONObject accountJson = JSON.parseObject(accountStr);
            BigDecimal amount = accountJson.
                    getJSONObject("data").getBigDecimal("total");
            BigDecimal waitIntrest = accountJson.getJSONObject("data")
                    .getBigDecimal("interestWait");
            BigDecimal yesterdayIntrest = accountJson.getJSONObject("data")
                    .getBigDecimal("interestYes");
            BigDecimal totalIntrest = accountJson.getJSONObject("data")
                    .getBigDecimal("income");
            AccountInfo accountInfo = new AccountInfo();
            accountInfo.setAmount(amount);
            accountInfo.setWaitIntrest(waitIntrest);
            accountInfo.setTotalIntrest(totalIntrest);
            accountInfo.setYesterdayIntrest(yesterdayIntrest);
            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            logger.error("[DuoDuoLiCaiSpiderHelper] parseAccountBalance fail!", e);
        }
        return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
    }
}
